<?php

namespace app\api\controller;

class upload extends common
{
    private $path = 'upload';
    public function uploadLogo()
    {
        $file = request()->file('file');
        $maxSize = 1024 * 1024;
        return $this->move($file, 'upload',$maxSize,['png','PNG', 'JPG','jpg', 'jpeg','JPEG'],'文件大小在10KM内');
//        dump($name);
//        exit();
//        if($name['url']){
//            return re_success('上传成功',$name);
//        }else{
//            return re_warning($name);
//        }
    }
    public function uploadImgs()
    {
        $file = request()->file('file');
        $maxSize = 1024 * 1024*2;
        return $this->move($file, 'upload',$maxSize,['png','PNG', 'JPG','jpg', 'jpeg','JPEG'],'文件大小在2M内');
//        return re_success('上传成功',$name);
    }

    public function uploadFiles()
    {
        $file = request()->file('file');
        $maxSize = 1024 * 1024 * 3;
        return $this->move($file, 'upload',$maxSize,['pdf'],'文件大小在3M内');
//        return re_success('上传成功',$name);
    }
    /**
     * 实现文件上传
     * @param object $file 上传的文件的对象信息
     * @param string $path 文件上传的目录
     * @return string|array 上传失败返回原因 成功返回文件的新名字数组
     */
    public function move($file, $path,$maxSize,$type)
    {

        try {
            // 判断逻辑错误
            if ($file->getSize() > $maxSize) {
                return re_error('上传文件超出了文件限制的大小'.$file->getSize().'---'.$maxSize);
                die();
            }

            // 判断文件类型
            $ext = strtolower($file->getOriginalExtension());
            if (!in_array($ext, $type, true)) {
                // 非法的文件类型
                return re_error('上传文件类型被拒绝或不符合');
                die();
            }

            $savename  = \think\facade\Filesystem::disk('public')->putFile( $this->path, $file);
            if ($savename) {
                $savename = str_replace("‘\’", '/', $savename);
                $savename = str_replace("\\", '/', $savename);
                return re_success('上传成功',['url'=>$savename,'size'=>$maxSize,'name'=>$file->getOriginalName()]);
            }else{
                // 上传失败获取错误信息
                return re_error('上传失败'.$file->getError());
                die();
            }
        } catch (\Exception $e) {
            return re_error('上传失败'.$e->getMessage() . $e->getLine());
        }
    }

    public function info(){
        return re_success('成功',['url'=>'storage/upload/20230906/8cee19ea776bd6629c9d1cf3e29fb836.png']);
    }
}